package cn.by.wms.service;

import cn.by.wms.dao.UserDao;
import cn.by.wms.dto.LoginDTO;
import cn.by.wms.dto.RegisterDTO;
import cn.by.wms.entity.User;
import cn.by.wms.entity.UserQuery;
import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.jwt.JWTUtil;
import cn.smart.core.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户表;(206_user)表服务实现类
 *
 * @author : heimi
 * @date : 2024-11-18
 */
@Service
@Slf4j
public class UserService {
    @Value("${cn.smart.tokenx.key}")
    private String tokenKey;

    @Autowired
    private UserDao userDao;

    public List<User> select(UserQuery query) {
        return userDao.selectAll(query);
    }

    public Integer insert(User user) {
        return userDao.insert(user);
    }

    public Integer update(User user) {
        return userDao.update(user);
    }

    public Integer delete(Integer id) {
        return userDao.delete(id);
    }

    private static TimedCache<String, Integer> map = CacheUtil.newTimedCache(3 * 60 * 1000);

    public Integer register(RegisterDTO registerDTO) {

        //1.拿到前台表单传来的数据
        String tel = registerDTO.getTel();
        String nickName = registerDTO.getNickName();
        String password = registerDTO.getPassword();
        String email = registerDTO.getEmail();
        Integer code = registerDTO.getCode();
        //2.对数据进行二次验证
        boolean boo = Validator.isMobile(tel);
        if (!boo) {
            BizException.throwBizException(410, "手机号不合法");
        }
        boo = Validator.isEmail(email);
        if (!boo) {
            BizException.throwBizException(411, "邮箱不合法");
        }
        boo = Validator.isNotEmpty(nickName);
        if (!boo) {
            BizException.throwBizException(412, "昵称不能为空");
        }

        if (!map.get("email").equals(code)) {
            BizException.throwBizException(413, "验证码错误，请重新输入");
        }
        //3.验证等幂性
        List<User> users = userDao.selectByTel(tel);
        if (ObjectUtil.isNotEmpty(users)) {
            BizException.throwBizException(414, "该手机号已存在，无法再次注册！");
        }
        //增加到数据库
        User user = new User();
        user.setTel(tel).setPassword(password).setNickName(nickName).setEmail(email);
        return userDao.insert(user);
    }

    public String login(LoginDTO loginDTO) {
        String password = loginDTO.getPassword();
        String tel = loginDTO.getTel();
        boolean boo = Validator.isMobile(tel);
        if (!boo) {
            BizException.throwBizException(410, "手机号不合法");
        }
        List<User> users = userDao.selectByTelAndPws(tel, password);
        if (ObjectUtil.isEmpty(users)) {
            BizException.throwBizException(415, "手机号或者密码错误，登陆失败");
        }
        User use=users.get(0);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", use.getId());
        map.put("tel", use.getTel().substring(0, 3) + "****" + use.getTel().substring(7, 11));
        map.put("nickName", use.getNickName());
        map.put("roles", use.getRoles().stream().map(r -> r.getName()).collect(Collectors.toList()));
        map.put("permissions", use.getPermissions().stream().map(r -> r.getName()).collect(Collectors.toList()));
        map.put("exp", System.currentTimeMillis() / 1000 + 60 * 60 * 24 * 10); //
        String token = JWTUtil.createToken(map, tokenKey.getBytes());
        System.out.println(token);
        return token;
    }

    public Integer sendCode(String email) {
        MailAccount account = new MailAccount();
        account.setHost("smtp.qq.com");
        account.setPort(465);
        account.setAuth(true);
        account.setFrom("768793659@qq.com");
        account.setUser("768793659@qq.com");
        account.setPass("ukgomqasulibbeae");
        account.setSslEnable(true);
        int code = RandomUtil.randomInt(1000,9999);
        map.put("email", code);
        MailUtil.send(account, CollUtil.newArrayList(email), "注册验证码", "【曹哥仓储管理平台】提醒您，尊敬的用户，您的验证码为："+code+"(3分钟有效)，转给他人将导致华为账号被盗和个人信息泄露，谨防诈骗。如非您操作请忽略!  ", false);
        return 1;


//        String url = "https://dfsns.market.alicloudapi.com/data/send_sms";
//        String appCode = "2c74feb3cd7e4231972cfc0a5b0d5487";
//        int code = RandomUtil.randomInt(1000, 9999);
//        map.put(tel, code);
//        log.info("您的验证码是:" + code);
        //        HttpRequest httpRequest = HttpRequest.post(url)
//                .header("Authorization", "AppCode " + appCode)
//                .body(StrUtil.format("content=code:{}&template_id=CST_ptdie100&phone_number={}",code,tel));
//        String body = httpRequest.execute().body();
//        String status = JSONUtil.parseObj(body).get("status").toString();
//        if (!status.equals("OK")) {
//            log.error("{}发送短信失败",tel);
//            BizException.throwBizException(505,"发送短信失败");
//        }
//        map.put("code", code);
//        return 0;
    }

}